package com.its.common.net.core.handler;

import com.its.common.net.core.dto.GenericNetDTO;
import com.its.common.net.server.channel.SocketAddrManager;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import java.net.InetSocketAddress;


/**
 * @Author xiaxp
 * @Date 9/21/22 17:26
 * @Description
 */
public abstract class BaseUdpHandler extends BaseGenericHandler<DatagramPacket> {
    protected SocketAddrManager socketAddrManager;

    @Override
    protected void extractSendSocketInfo(ChannelHandlerContext ctx, GenericNetDTO<DatagramPacket> data) {
        DatagramPacket packet = data.getData();
        InetSocketAddress address = new InetSocketAddress(packet.sender().getHostString(),packet.sender().getPort());
        data.getSender().address = address.getHostString();
        data.getSender().port = address.getPort();
        //TODO UDP只能从报文中获取发送端的地址和端口，为给客户端留存，需放入内存
        //TODO 完善 自定义客户端淘汰机制
        if(null != socketAddrManager) {
            socketAddrManager.addInetSocketAddress(address);
        }
    }

    @Override
    protected byte[] extract2bytes(DatagramPacket packet) {
        ByteBuf buf = packet.content();
        return byteBuf2bytes(buf);
    }

    @Override
    public abstract void handleData(ChannelHandlerContext ctx, GenericNetDTO<DatagramPacket> data);

}
